const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../../utils/config.js'
import {
  validateEmoji,
  validateSpecial
} from '../../../../../utils/validate.js'
import {
  reqSpaceEdit,
  reqSpaceImage,
  reqDeviceBySpaceId,
  reqDeviceByImei,
  reqDeviceAdd,
  reqDeviceUnBind,
  reqAlarmReceiverList,
  reqReceiverSpaceAdd,
  reqAlarmReceiverBySpaceId
} from '../../../../../request/api'
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    spaceInfo: {
      type: Object,
      value: {},
    }
  },


  data: {
    form: {
      id: '',
    },
    disabledBtn: false,
  },

  observers: {
    'spaceInfo': function (newVal) {
      this.setData({
        'form.id': newVal.id,
      })
      if (newVal.id) {
        this.getAlarmReceiverBySpaceId()
      }
    }
  },


  methods: {
    /* --------------------------------设备开始-------------------------- */
    // 空间id获取安装设备
    async getAlarmReceiverBySpaceId() {
      const res = await reqDeviceBySpaceId(this.data.form.id)
      let {
        rows
      } = res.data
      let arr = []
      rows.forEach((item, index) => {
        arr.push({
          id: index,
          devicePrimaryId: item.id,
          imei: item.imei,
          type: item.productName,
        })
      })
      this.setData({
        imeiList: arr
      })
    },
    // 点击新增一条设备输入框
    clickAddDevice() {
      let {
        imeiList
      } = this.data
      let count = 0
      let length = imeiList.length
      imeiList.forEach(item => {
        if (item.devicePrimaryId) {
          count++
        }
      })
      if (length - count >= 5) return showMsg("一次最多新增5台设备")
      // let id = imeiList[imeiList.length - 1].id + 1
      let id = imeiList.length === 0 ? 0 : imeiList[imeiList.length - 1].id + 1
      imeiList.push({
        id,
        imei: '',
        type: ''
      })
      this.setData({
        imeiList
      })
    },
    // 判断imei是否已存在
    async getDeviceByImei(id, imei) {
      let {
        imeiList
      } = this.data
      const res = await reqDeviceByImei(imei)
      if (res.code === 12020 || res.code === 12021) {
        // 清空操作
        imeiList.forEach(item => {
          if (item.id === id) {
            item.imei = ''
            item.type = ''
          }
        })
        // imeiList.forEach(item => {
        //     if (item.id === id) {
        //         item.imei = imei
        //         // item.type = res.data.row.productName
        //     }
        // })
        this.setData({
          imeiList
        })
        showMsg(res.message)
        return
      }
      if (res.code !== 20000) return showMsg(res.message)
      imeiList.forEach(item => {
        if (item.id === id) {
          item.imei = imei
          item.type = res.data.row.productName
        }
      })
      this.setData({
        imeiList
      })
      this.reqReceiverSpace() // 安装点设备修改
    },
    // 获取设备imei
    imeiChange(e) {
      let {
        id
      } = e.target.dataset
      let {
        value
      } = e.detail
      if (value.length >= 15) {
        this.getDeviceByImei(id, value)
      }
      if (value.length <= 0) {
        // 删除到没有时，清除imei和类型
        let {
          imeiList
        } = this.data
        imeiList.forEach(item => {
          if (item.id === id) {
            item.imei = ''
            item.type = ''
          }
        })
        this.setData({
          imeiList
        })
      }
    },
    // js判断字符串是否为JSON格式
    isjson(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            return false;
          }

        } catch (e) {
          console.log('error：' + str + '!!!' + e);
          return false;
        }
      }
      console.log('It is not a string!')
    },
    /**
     * @name:  扫码imei
     * @msg: 掉接口时记得询问清楚截取方法
     * @return {*}
     */
    imeiScan(e) {
      let that = this
      let {
        id
      } = e.target.dataset
      let qrcode = ''
      wx.scanCode({
        success(res) {
          qrcode = res.result;
          if (!qrcode) return showMsg('扫描失败，请重新扫描')
          if (qrcode.length >= 3) {
            if (that.isjson(qrcode)) {
              const result = JSON.parse(qrcode);
              // JSON字符格式
              that.setData({
                searchValue: result.ID, //威视达康摄像机取值，后续看需求更改 lc
              })
              that.getDeviceByImei(id, result.ID)
            } else {
              // 非JSON格式
              that.setData({
                searchValue: qrcode,
              })
              that.getDeviceByImei(id, qrcode)
            }
          } else {
            showMsg('扫描失败，请重新扫描')
            return
          }
        }
      })
    },
    // 扫码后赋值imei
    imeiScanChange(id, code) {
      let {
        imeiList
      } = this.data
      imeiList.forEach(item => {
        if (item.id === id) {
          item.imei = code
        }
      })
      this.setData({
        imeiList
      })
    },
    // 清除imei
    imeiClear(e) {
      let {
        info
      } = e.target.dataset
      let {
        imeiList
      } = this.data
      imeiList.forEach((item, index) => {
        if (item.id === info.id) {
          if (info.devicePrimaryId) {
            this.getDeviceUnBind(info.devicePrimaryId, index)
          } else {
            item.imei = ''
            item.type = ''
          }
        }
      })
      this.setData({
        imeiList
      })
    },

    getDeviceUnBind(id, index) {
      let {
        imeiList
      } = this.data
      Dialog.confirm({
          title: '温馨提示',
          message: '此操作将解绑该设备，是否继续？',
        })
        .then(async () => {
          const res = await reqDeviceUnBind({
            userId: app.globalData.userId,
            id
          })
          if (res.code != 20000) return showMsg(res.message);

          imeiList.splice(index, 1)
          imeiList.forEach((item, index) => {
            item.id = index
          })
          this.setData({
            imeiList
          })
          showMsg("解绑成功")
        })
        .catch(() => {});
    },

    // 确定修改设备
    async reqReceiverSpace() {
      let {
        imeiList,
        form
      } = this.data
      let arr = imeiList.map(item => {
        return item.imei
      })
      let list = arr.filter(Boolean)
      if (list.length <= 0) return showMsg("请输入设备编码")
      let params = {
        spaceId: this.data.form.id,
        userId: app.globalData.userId,
        imeiList: list
      }
      const res = await reqDeviceAdd(params)
      if (res.code != 20000) return showMsg(res.message);
      // showMsg("编辑成功", "success")
      // this.setData({
      //     disabledBtn: true
      // })
      // setTimeout(() => {
      //     wx.navigateBack({
      //         delta: 1,
      //     })
      // }, 2000)
    },


    /* --------------------------------设备结束-------------------------- */
  }
})